package com.cheejee.goodscenter.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.carry.common.tool.ListTool;
import com.cheejee.goodscenter.dao.GoodsCustomPropertiesMapper;
import com.cheejee.goodscenter.module.entity.GoodsCustomProperties;
import com.cheejee.goodscenter.service.GoodsCustomPropertiesService;
import com.cheejee.goodscenter.service.exception.DataNotExistException;
import com.cheejee.goodscenter.validated.Check;
import com.cheejee.goodscenter.validated.InsertGroup;
import com.cheejee.goodscenter.validated.UpdateGroup;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import cn.hutool.core.collection.CollectionUtil;


/**
 * @author CARRY
 * @Date 2020年10月28日上午2:03:33
 */
@Service
public class GoodsCustomPropertiesServiceImpl implements GoodsCustomPropertiesService {
	
	@Resource
	private GoodsCustomPropertiesMapper mapper;
	
	@Override
	public Page<GoodsCustomProperties> queryGoodsCustomProperties(Long goodsId, String propertiesName, int pageNum, int pageSize) {

		return PageHelper.startPage(pageNum, pageSize).doSelectPage(() -> mapper.selectBySelective(goodsId, propertiesName));
	}

	@Override
	public GoodsCustomProperties queryGoodsCustomPropertiesById(Long id) {

		return mapper.selectByPrimaryKey(id);
	}

	@Override
	@Check(message = "新增的商品自定义属性不能为空", group = InsertGroup.class)
	public int addGoodsCustomProperties(List<GoodsCustomProperties> properties) {
		ListTool.removeNull(properties);
		
		return mapper.insertMany(properties);
	}
	
	@Override
	@Check(message = "新增的商品自定义属性不能为空", group = InsertGroup.class)
	public int addGoodsCustomProperties(GoodsCustomProperties properties) {

		return mapper.insertSelective(properties);
	}

	@Override
	@Check(message = "修改的商品自定义属性不能为空", group = UpdateGroup.class)
	public int changeGoodsCustomProperties(GoodsCustomProperties properties) {
		checkExist(properties.getId());

		return mapper.updateByPrimaryKeySelective(properties);
	}

	@Override
	@Transactional
	@Check(message = {"商品ID不能为空", "商品自定义属性不能为空"}, group = UpdateGroup.class, IgnoreEmptyList = true)
	public int changeGoodsCustomProperties(Long goodsId, List<GoodsCustomProperties> properties) {
		mapper.deleteByGoodsId(goodsId);
		
		if(CollectionUtil.isEmpty(properties)) {
			return 0;
		}
		
		return mapper.insertMany(properties);
	}
	
	private void checkExist(Long id) {
		if(mapper.selectByPrimaryKey(id) == null) {
			throw new DataNotExistException("商品自定义属性不存在");
		}
	}

	@Override
	public int deleteGoodsCustomProperties(Long... id) {
		
		return mapper.deleteById(id);
	}

}
